package com.distribute.core.netty.retry;

import java.util.Random;

/**
 * 重试策略实现
 *
 * @author chennengcheng
 * @date 2021-09-22 15:49
 * @remark
 */

public class ExponentialBackOffRetry implements RetryPolicy {

    private static final int MAX_RETRIES_LIMIT = Integer.MAX_VALUE;
    private static final int DEFAULT_MAX_SLEEP_MS = Integer.MAX_VALUE;

    private final Random random = new Random();
    private final long baseSleepTimeMs;
    private final int maxRetries;
    private final int maxSleepMs;

    public ExponentialBackOffRetry(int baseSleepTimeMs, int maxRetries) {
        this(baseSleepTimeMs, maxRetries, DEFAULT_MAX_SLEEP_MS);
    }

    public ExponentialBackOffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs) {
        this.maxRetries = maxRetries;
        this.baseSleepTimeMs = baseSleepTimeMs;
        this.maxSleepMs = maxSleepMs;
    }

    @Override
    public boolean allowRetry(int retryCount) {
        if (retryCount < maxRetries) {
            return true;
        }
        return false;
    }

    @Override
    public long getSleepTimeMs(int retryCount) {
        if (retryCount < 0) {
            throw new IllegalArgumentException("retries count must greater than 0.");
        }
//
//        long sleepMs = baseSleepTimeMs * Math.max(1, random.nextInt(1 << retryCount));
//        if (sleepMs > maxSleepMs) {
//            System.out.printf("Sleep extension too large (%d). Pinning to %d%n", sleepMs, maxSleepMs);
//            sleepMs = maxSleepMs;
//        }

        return baseSleepTimeMs;
    }
}